import json
import os
import sys
from common.time_bdp import time_bdp
from core.result_base import ResultBase
from api.view import view
from common.logger import logger
from common.user_agent import useragent
import urllib3
urllib3.disable_warnings()

BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(BASE_PATH)



def view_allpreview(access_token,info,field_usage,generator_type,_t=time_bdp.time_stamp_13(),_xsrf=""):
    """
    预览
    :param info:
    :param field_usage: field_usage
    :param generator_type: generator_type
    :param _t: 13位的时间戳
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    info_payload = {
        "info":info,
        "field_usage":field_usage
    }

    payload = {
        "info":json.dumps(info_payload),
        "generator_type":generator_type,
        "_t": _t,
        "_xsrf":_xsrf
    }
    headers = {
        "User-Agent": useragent.get_user_agent_one(),
        "Cookie":"access_token={}".format(access_token)
  }

    res = view.allpreview(params=payload, headers=headers)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("allpreview ==>> 返回结果 ==>> {}".format(result.response.text))
    return result


def view_allcreate(access_token,tb_name,field_usage,id,name,info,generator_type,folder_id="folder_root",_t=time_bdp.time_stamp_13(),_xsrf=""):
    """
    allcreate
    :param info:
    :param field_usage: field_usage
    :param generator_type: generator_type
    :param _t: 13位的时间戳
    :param _xsrf :
    :return: 自定义的关键字返回结果 result
    """
    result = ResultBase()
    info_payload = {
        "tb_name":tb_name,
        "field_usage":field_usage,
        "scheduler_conf":{"sync_config":"","mode":2},
        "info":info
    }

    param_tb_payload = {
        "id":id,
        "name":name
    }
    payload = {
        "folder_id":folder_id,
        "generator_type":generator_type,
        "info":json.dumps(info_payload),
        "param_tb":json.dumps([param_tb_payload]),
        "_t": _t,
        "_xsrf":_xsrf
    }

    headers = {
        "User-Agent": useragent.get_user_agent_one(),
        "Cookie":"access_token={}".format(access_token)
  }

    res = view.allcreate(params=payload, headers=headers)
    result.success = False
    if res.json()["status"] == "0":
        result.success = True
    else:
        result.error = "接口返回码是 【 {} 】, 返回信息：{} ".format(res.json()["errstr"], res.json())
    result.payload = res.json()
    result.response = res
    logger.info("allcreate ==>> 返回结果 ==>> {}".format(result.response.text))
    return result
















